package com.qingfeng.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import com.qingfeng.client.VO.OrderExcelVo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

/**
 *
 * 自定义单元格合并策略
 * 合并code相同值的单元格
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/4/7 2:09 下午
 */
public class ExcelMergeStrategy extends AbstractMergeStrategy {

    /**
     * Each row
     */

    List<OrderExcelVo> list;

    public ExcelMergeStrategy(List<OrderExcelVo> list) {
        this.list = list;
    }


    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {
        if (relativeRowIndex == null) {
            return;
        }

        int lastLow = cell.getRowIndex();

        boolean flag = true;
        OrderExcelVo orderExcelVo;
        OrderExcelVo preVo;
        while (flag) {
            if (lastLow >= list.size()) {
                break;
            }
            preVo = list.get(lastLow-1);
            orderExcelVo = list.get(lastLow);
            if (cell.getColumnIndex() == 0
                    || cell.getColumnIndex() == 1
                    || cell.getColumnIndex()==2
                    || cell.getColumnIndex()==6
                    || cell.getColumnIndex()==7
                    || cell.getColumnIndex()==8
                    || cell.getColumnIndex()==9
                    || cell.getColumnIndex()==10
                    || cell.getColumnIndex()==11
                    || cell.getColumnIndex()==12
            ) {
                //如果code相同则进行合并
                if (preVo.getCode().equals(orderExcelVo.getCode())) {
                    lastLow++;
                } else {
                    flag = false;
                }
            }else {
                break;
            }
        }
        if (lastLow>cell.getRowIndex()) {
            /**
             * int firstRow, 开始行
             * int lastRow, 结束行
             * int firstCol, 开始列
             * int lastCol 结束列
             */
            CellRangeAddress cellRangeAddress = new CellRangeAddress(cell.getRowIndex(),
                    lastLow, cell.getColumnIndex(), cell.getColumnIndex());
            sheet.addMergedRegionUnsafe(cellRangeAddress);
        }

        return;
    }
}
